package client.ressources;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;

import javax.swing.ImageIcon;
import javax.swing.JOptionPane;

public class TCPRequest {
	
	private Socket connectionSocket = null;
	private DataOutputStream out = null;
	private DataInputStream in = null;
	private String response;
	private String serverAddress = "localhost";
	private int serverPort = 4444;
	
	public TCPRequest (String requestType) {
		
		try {
			
			connectionSocket = new Socket(serverAddress, serverPort);
			out = new DataOutputStream(connectionSocket.getOutputStream());
			in = new DataInputStream(connectionSocket.getInputStream());
			
			out.writeUTF(requestType);
			System.out.println("Phase #2: TCP request sent.");
			
			response = in.readUTF();
		} catch (SocketException s) {
			ImageIcon icon = new ImageIcon(getClass().getResource("400px-Warning_icon.svg.png"));
			JOptionPane.showMessageDialog(null,
							"The connection attempt failed.\nPlease check your internet connection!",
							"ERROR", JOptionPane.ERROR_MESSAGE, icon);
			System.err.println("Connection Exception: " + s.getMessage());
			System.exit(0);
		} catch (UnknownHostException h) {
			System.err.print("Host Exception: " + h.getMessage());
		} catch (EOFException e) {
			System.err.print("EOF Exception: " + e.getMessage());
		} catch (IOException i) {
			System.err.print("IO Exception: " + i.getMessage());
		}
	}
	
	public String getResponse() {
		return response;
	}
}
